import axios from 'axios';

export default {
  async download(path) {
    try {
      const request = axios.create({
        responseType: 'blob', // 关键：指定响应类型为blob
        headers: {
          token: sessionStorage.getItem('authorization'),
        },
      });
      const response = await request.post(
        `/Api/FileDownload?path=${path}`
      );
      console.log('file download success');
      this.handleFileResponse(response);
    } catch (response) {
      console.log('file download err');
      if (response instanceof Blob) {
        this.handleFileResponse(response);
      } else {
      }
    }
  },
  handleFileResponse(response) {
    console.log(response, typeof response);
    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'downloadfile';

    if (contentDisposition) {
      // 解析文件名 (不同浏览器可能有不同格式)
      const match = contentDisposition.match(/filename="?(.+)"?/);
      if (match && match[1]) {
        fileName = decodeURIComponent(match[1]);
      }
    }

    // 创建blob对象
    const blob = new Blob([response.data]);

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.target = '_blank';
    a.download = fileName;

    // 模拟点击下载
    document.body.appendChild(a);
    a.click();

    // 清理资源
    setTimeout(() => {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  },
}
